package org.jeecg.modules.gqHealth.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.gqHealth.entity.AppBanner;
import org.jeecg.modules.gqHealth.entity.FileResultVo;
import org.jeecg.modules.gqHealth.entity.GqRealnameInfo;
import org.jeecg.modules.gqHealth.service.IAppBannerService;
import org.jeecg.modules.gqHealth.service.IGqRealnameInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecg.modules.utils.CommonUtil;
import org.jeecg.modules.utils.SyssetConfConstants;
import org.jeecg.modules.utils.WxConstant;
import org.jeecg.modules.utils.WxUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 用户实名信息表
 * @Author: jeecg-boot
 * @Date: 2024-05-08
 * @Version: V1.0
 */
@Api(tags = "用户实名信息表")
@RestController
@RequestMapping("/gqHealth/gqRealnameInfo")
@Slf4j
public class GqRealnameInfoController extends JeecgController<GqRealnameInfo, IGqRealnameInfoService> {
    @Autowired
    private IGqRealnameInfoService gqRealnameInfoService;
    @Resource
    private IAppBannerService appBannerService;

    @Resource
    private ISysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param gqRealnameInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "用户实名信息表-分页列表查询")
    @ApiOperation(value = "用户实名信息表-分页列表查询", notes = "用户实名信息表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<GqRealnameInfo>> queryPageList(GqRealnameInfo gqRealnameInfo,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<GqRealnameInfo> queryWrapper = QueryGenerator.initQueryWrapper(gqRealnameInfo, req.getParameterMap());
        Page<GqRealnameInfo> page = new Page<GqRealnameInfo>(pageNo, pageSize);
        IPage<GqRealnameInfo> pageList = gqRealnameInfoService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param gqRealnameInfo
     * @return
     */
    @AutoLog(value = "用户实名信息表-添加")
    @ApiOperation(value = "用户实名信息表-添加", notes = "用户实名信息表-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:gq_realname_info:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody GqRealnameInfo gqRealnameInfo) {
        QueryWrapper<GqRealnameInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id",gqRealnameInfo.getCardId());
        GqRealnameInfo one = gqRealnameInfoService.getOne(queryWrapper);
        if (null != one && StringUtils.isNotEmpty(one.getId())){
            return Result.error("已经提交过实名");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Object num = redisUtil.get("realname::" + sysUser.getUsername());
        Integer aNum = 0;
        if (null != num){
            aNum = (Integer) num;
        }
        if (aNum> SyssetConfConstants.AUTH_ORC_USER_CHECK_LIMIT){
            return Result.error("今天认证超限制");
        }
        Integer retCode = CommonUtil.getIdcardValidate(gqRealnameInfo.getRealName(),gqRealnameInfo.getCardId());
        aNum ++;
        redisUtil.set("realname::" + sysUser.getUsername(),aNum,CommonUtil.getNowToNextDaySeconds());
        if (retCode != 200){
            return Result.error("认证失败,请检查身份证和姓名是否正确");
        }

        SysUser byId = sysUserService.getById(sysUser.getId());
        byId.setRealname(gqRealnameInfo.getRealName());
        byId.setIdcard(gqRealnameInfo.getCardId());
        sysUserService.updateById(byId);
        gqRealnameInfoService.save(gqRealnameInfo);
        return Result.OK("添加成功！");
    }

    /**
     * 查询用户实名信息
     *
     * @param
     * @return
     */
    @AutoLog(value = "用户实名信息表-查询用户实名信息")
    @ApiOperation(value = "用户实名信息表-查询用户实名信息", notes = "用户实名信息表-查询用户实名信息")
    //@RequiresPermissions("org.jeecg.modules.demo:gq_realname_info:add")
    @PostMapping(value = "/userReal")
    public Result<?> userReal() {
        QueryWrapper<GqRealnameInfo> queryWrapper = new QueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("create_by",sysUser.getUsername());
        GqRealnameInfo one = gqRealnameInfoService.getOne(queryWrapper);
        if (null == one || StringUtils.isEmpty(one.getId())){
            return Result.error("暂无数据");
        }

        return Result.ok(one);
    }

    /**
     * 编辑
     *
     * @param gqRealnameInfo
     * @return
     */
    @AutoLog(value = "用户实名信息表-编辑")
    @ApiOperation(value = "用户实名信息表-编辑", notes = "用户实名信息表-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:gq_realname_info:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody GqRealnameInfo gqRealnameInfo) {
        gqRealnameInfoService.updateById(gqRealnameInfo);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户实名信息表-通过id删除")
    @ApiOperation(value = "用户实名信息表-通过id删除", notes = "用户实名信息表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:gq_realname_info:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        gqRealnameInfoService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户实名信息表-批量删除")
    @ApiOperation(value = "用户实名信息表-批量删除", notes = "用户实名信息表-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:gq_realname_info:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.gqRealnameInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "用户实名信息表-通过id查询")
    @ApiOperation(value = "用户实名信息表-通过id查询", notes = "用户实名信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<GqRealnameInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        GqRealnameInfo gqRealnameInfo = gqRealnameInfoService.getById(id);
        if (gqRealnameInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(gqRealnameInfo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param gqRealnameInfo
     */
    //@RequiresPermissions("org.jeecg.modules.demo:gq_realname_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GqRealnameInfo gqRealnameInfo) {
        return super.exportXls(request, gqRealnameInfo, GqRealnameInfo.class, "用户实名信息表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("gq_realname_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GqRealnameInfo.class);
    }

//	=========首页接口=====================

    @ApiOperation(value = "首页-实名信息状态", notes = "首页-实名信息状态")
    @GetMapping(value = "/realNameStatus")
	public Result<?> realNameStatus(){
//		统计实名认证各状态人数
		return gqRealnameInfoService.realNameConfirm();
	}



//    ===================== app 接口 ================================
    @ApiOperation(value = "app-首页banner图获取", notes = "app-首页banner图获取")
    @GetMapping(value = "/getBanner")
    public Result<?> getBanner(){
        LambdaQueryWrapper<AppBanner> appBannerWrapper = new LambdaQueryWrapper<>();
        appBannerWrapper.eq(AppBanner::getStatus,1);
        appBannerWrapper.orderByAsc(AppBanner::getSort);
        List<AppBanner> list = appBannerService.list(appBannerWrapper);
        if(null == list || list.isEmpty()){
            return Result.error(-1,"没有获取到Banner图数据");
        }
        return Result.OK(list);
    }

    /**
     * 获取页面需要的配置信息的参数
     * 获取用户微信地理位置信息
     * @param url
     * @return
     */
    @ResponseBody
    @CrossOrigin
    @RequestMapping(value = "/getJsTicket")
    public Result<?> getWeJsTicket(String url) {
        //1、获取AccessToken
        String accessToken = WxUtils.getAccessToken(WxConstant.APPID,WxConstant.APPSECRET);

        //2、获取Ticket
        String jsapi_ticket = WxUtils.getTicket(accessToken);
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;

        //6、将字符串进行sha1加密
        String signature =WxUtils.SHA1(str);

        JSONObject map = new JSONObject();
        try {
            // 获取微信signature
            map.put("appId", WxConstant.APPID);
            map.put("timestamp", timestamp);
            map.put("nonceStr", noncestr);
            map.put("signature", signature);
        } catch (Exception e) {
            return Result.error("数据异常");
            //this.logger.error(e.getMessage());
        }
        String json = SecurityUtil.jiami(map.toString());

        return Result.OK("",map);
    }

//
//    /**
//     * 图片上传
//     */
//    @ApiOperation(value = "图片上传")
//    @RequestMapping(value = "/image", method = RequestMethod.POST)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "typeImg", value = "1身份证正面"),
//            @ApiImplicitParam(name = "model", value = "模块 用户user,商品product,微信wechat,news文章"),
//            @ApiImplicitParam(name = "pid", value = "分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列 ", allowableValues = "range[0,1,2,3,4,5,6,7,8]")
//    })
//    public Result<FileResultVo> image(MultipartFile multipart,@RequestParam(value = "model") String model,
//                                            @RequestParam(value = "pid") Integer pid,
//                                            @RequestParam(name = "typeImg", defaultValue = "0",required = false) Integer typeImg, HttpServletRequest request) throws IOException {
//        FileResultVo resultVo = uploadService.imageUpload(multipart, model, pid);
//        if (typeImg == 1){
//            Integer uid = userService.getUserId();
//            Integer count = checkIdcardRecordService.getTodayCount(uid, 1, null);
//            if (count >= SyssetConfConstants.AUTH_ORC_USER_ORC_LIMIT){
//                return CommonResult.failed("今天识别超限制");
//            }
//            AuthenticationResponse authenticationResponse = CommonUtil.getAuthenticationOrcIdcard("", SyssetConfConstants.OSS_IMG_URL+""+resultVo.getUrl());
//            if (authenticationResponse != null) {
//                String ip = CrmebUtil.getClientIp(request);
//                LbCheckIdcardRecordEntity checkIdcardRecordEntity = new LbCheckIdcardRecordEntity();
//                checkIdcardRecordEntity.setUid(uid);
//                checkIdcardRecordEntity.setName(authenticationResponse.getName());
//                checkIdcardRecordEntity.setNumber(authenticationResponse.getNumber());
//                checkIdcardRecordEntity.setIp(ip);
//                checkIdcardRecordEntity.setCreateTime(DateUtil.nowDateTime());
//                checkIdcardRecordEntity.setType(1);
//                checkIdcardRecordService.add(checkIdcardRecordEntity);
//                Map<String, Object> map = new HashMap<>();
//                map.put("name", authenticationResponse.getName());
//                map.put("number", authenticationResponse.getNumber());
//                resultVo.setExtData(map);
//            }
//        }
//
//        return CommonResult.success(resultVo);
//    }
}
